// DrawPoint
/*
绘制点
 */
class DrawPoint {
  constructor(arg) {
    this.viewer = arg.viewer
    this.Cesium = arg.Cesium
    this.callback = arg.callback
    this._point = null  //最后一个点
    this._pointData = null//点数据用于构造点
    this._entities = [] //脏数据
  }

  //返回最后活动点
  get point() {
    return this._point
  }

  //加载点
  loadPoint(data) {
    return this.createPoint(data)
  }

  //返回点数据用于加载点
  getData() {
    return this._pointData
  }

  //开始绘制
  startCreate(option) {
    var $this = this
    this.handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.cesiumViewer.scene.canvas)
    this.handler.setInputAction(function(evt) { //单机开始绘制
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (!cartesian) return
      var point = $this.createPoint(cartesian, option)
      $this._pointData = cartesian
      $this._point = point
      if (typeof $this.callback == 'function') {
        $this.callback(point)
      }
    }, $this.Cesium.ScreenSpaceEventType.LEFT_CLICK)
  }

  //创建点
  createPoint(cartesian, option) {
    var $this = this
    var pointColor = option.color ? option.color : 'rgb(255, 0, 0)'
    var pointSize = option.pointSize ? option.pointSize : 5
    var outlineWidth = option.outlineWidth ? option.outlineWidth : 0
    var outlineColor = option.outlineColor ? option.outlineColor : 'rgb(255, 255, 255)'
    var point = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
      position: cartesian,
      point: {
        pixelSize: pointSize,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        color: $this.Cesium.Color.fromCssColorString(pointColor),
        outlineWidth: outlineWidth,
        outlineColor: $this.Cesium.Color.fromCssColorString(outlineColor),
      }
    })
    $this._entities.push(point) //加载脏数据
    return point
  }

  //销毁鼠标事件
  destroy() {
    if (this.handler) {
      this.handler.destroy()
      this.handler = null
    }
  }

  //清空实体对象
  clear() {
    for (var i = 0; i < this._entities.length; i++) {
      this.viewer.dataSourceDisplay._defaultDataSource.entities.remove(this._entities[i])
    }
    this._entities = []
    this._point = null
  }

  getCatesian3FromPX(px) {
    var cartesian
    var ray = this.viewer.cesiumViewer.camera.getPickRay(px)
    if (!ray) return null
    cartesian = this.viewer.cesiumViewer.scene.globe.pick(ray, this.viewer.cesiumViewer.scene)
    if (!cartesian) {
      cartesian = this.viewer.cesiumViewer.camera.pickEllipsoid(px, this.viewer.cesiumViewer.scene.globe.ellipsoid)
    }
    return cartesian
  }
}

export default DrawPoint
